package com.zengqingfa.fastdfs.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.zengqingfa.fastdfs.service.FastDfsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author zengqingfa
 * @className FastDfsServiceImpl
 * @description
 * @create 2021/11/20 17:38
 */
@Service
@Slf4j
public class FastDfsServiceImpl implements FastDfsService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Value("${upload.base-url}")
    private String baseUrl;


    @Override
    public String uploadFile(MultipartFile file) {
        //校验文件
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
                throw new RuntimeException("上传文件不是图片");
            }
        } catch (IOException e) {
            log.error("校验文件内容失败....{}", e);
            throw new RuntimeException("校验文件内容失败" + e.getMessage());
        }
        try {
            // 获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 上传到FastDFS
            //上传略缩图
            // StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), extension, null);
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 返回路径
            return baseUrl + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败！....{}", e);
            throw new RuntimeException("【文件上传】上传文件失败！" + e.getMessage());
        }
    }

    @Override
    public void downloadFile(String url) {
        try {
            String path = getPath(url);
            String group = getGroup(path);
            path = getPath(path, group);
            byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());
            FileOutputStream stream = new FileOutputStream("3_150x150.jpg");
            stream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【文件下载】文件下载失败！....{}", e);
        }
    }


    @Override
    public void deleteFile(String url) {
        try {
            String path = getPath(url);
            String group = getGroup(path);
            path = getPath(path, group);
            fastFileStorageClient.deleteFile(group, path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            log.error("【文件删除】文件删除失败！....{}", e);
        }
    }

    @Override
    public FileInfo queryFileInfo(String url) {
        FileInfo fileInfo = null;
        try {
            String path = getPath(url);
            String group = getGroup(path);
            path = getPath(path, group);
            fileInfo = fastFileStorageClient.queryFileInfo(group, path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            log.error("【文件删除】文件删除失败！....{}", e);
        }
        return fileInfo;
    }

    private String getGroup(String path) {
        String[] split = path.split("/");
        return split[1];
    }

    private String getPath(String url) throws MalformedURLException {
        URL tempUrl = new URL(url);
        // path:   /group1/M00/00/00/L2By4WGY1G6AU_xKAAW9E9z-s-4378.png
        return tempUrl.getPath();
    }

    private String getPath(String path, String group) throws MalformedURLException {
        path = path.substring(path.indexOf("/") + group.length() + 2);
        return path;
    }

    public static void main(String[] args) {
        String path = "/group1/M00/00/00/L2By4WGY1G6AU_xKAAW9E9z-s-4378.png";
        String[] split = path.split("/");
        System.out.println(path.indexOf("/"));
        System.out.println(path.substring(path.indexOf("/") + split[1].length() + 2));
    }
}